package com.fgi.springframework.context.support;

import com.fgi.springframework.beans.BeansException;
import com.fgi.springframework.beans.factory.config.BeanPostProcessor;
import com.fgi.springframework.context.ApplicationContext;
import com.fgi.springframework.context.ApplicationContextAware;

/**
 * @author HanXu
 * @date 2022/12/1
 *
 * 包装处理器
 *
 * 由于 ApplicationContext 的获取并不能直接在创建 Bean 时候就可以拿到，所以需要在 refresh 操作时，把 ApplicationContext 写入到一个包装的 BeanPostProcessor 中去，
 * 再由 AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization 方法调用。
 *
 **/
public class ApplicationContextAwareProcessor implements BeanPostProcessor {

    private final ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * bean -- 继承了 BeanNameAware, BeanClassLoaderAware, ApplicationContextAware, BeanFactoryAware  其中一个或者多个的实例
     * 该实例一定会补充 applicationContext(或者其它的对应的属性, 比如 BeanClassLoader, BeanFactory), 这个方法就是赋值用的
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ApplicationContextAware){
            ((ApplicationContextAware) bean).setApplicationContext(applicationContext);
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}
